package com.wuliupai.delivery.wuliupaidelivery.activity;

import android.content.ClipboardManager;
import android.content.Context;
import android.os.Vibrator;

import com.wuliupai.delivery.wuliupaidelivery.App;
import com.wuliupai.delivery.wuliupaidelivery.R;
import com.wuliupai.delivery.wuliupaidelivery.bean2.qr.QRCodeBean;
import com.wuliupai.delivery.wuliupaidelivery.constants.PageFlag;
import com.wuliupai.delivery.wuliupaidelivery.utils.JsonUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.LogUtils;
import com.wuliupai.delivery.wuliupaidelivery.utils.StringUtils;

import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EActivity;
import org.androidannotations.annotations.Extra;
import org.androidannotations.annotations.ViewById;

import cn.bingoogolapple.qrcode.core.QRCodeView;
import cn.bingoogolapple.qrcode.zxing.ZXingView;

@EActivity(R.layout.activity_scan_qrbar)
public class ScanQRBarActivity extends AppBaseActivity implements QRCodeView.Delegate {

    @ViewById(R.id.zXingView)
    ZXingView mQRCodeView;
//    @ViewById(R.id.btn_openOrCloseFlashLight)
//    Button btn_openOrCloseFlashLight;

    @Extra("orderCode")
    String orderCode = "";

    private boolean isFlashOpened = false;

    private ScanQRBarActivity _activity;
//    private LocalBroadcastManager lbm;

    @AfterViews
    void onPageStart() {
        _activity = this;
//        lbm = LocalBroadcastManager.getInstance(this);
        setDefaultTitle(this, R.string.string_scan_title);
        mQRCodeView.setDelegate(this);
    }

    @Override
    protected void onStart() {
        super.onStart();
        mQRCodeView.startCamera();
        mQRCodeView.startSpot();
    }

    @Override
    protected void onStop() {
        mQRCodeView.stopCamera();
        super.onStop();
    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        animUtils.leftOutAnimation(this);
    }

    @Override
    protected void onDestroy() {
        mQRCodeView.onDestroy();
        super.onDestroy();
    }

    /**
     * 开/关闪光灯
     */
    @Click(R.id.btn_openOrCloseFlashLight)
    void onOpenOrCloseFlashFlightClick() {
        if (isFlashOpened) {
            mQRCodeView.closeFlashlight();
            isFlashOpened = false;
        } else {
            mQRCodeView.openFlashlight();
            isFlashOpened = true;
        }
    }

    private void vibrate() {
        Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
        vibrator.vibrate(200);
    }

    @Override
    public void onScanQRCodeSuccess(String result) {
        vibrate();

        handleQrCode(result, 1);
//        LogUtils.log("扫码结果~~" + result);
//        if (result.contains(Value.LabelHeaderFlag)) {
//            result = result.substring(Value.LabelHeaderFlag.length());
//            final String orderCode = result;
//            if (Form_OrderDetailPage == whichPage) {
//                //从订单详情跳转过来
//                if (result.equals(orderCode)) {
//                    //订单号与扫码结果一致
//                    new AlertDialog.Builder(this)
//                            .setTitle("提示")//设置对话框标题
//                            .setCancelable(false)
//                            .setMessage("是否装车？")
//                            .setPositiveButton("确认装车", (dialog, which) -> {
//                                toConfirmOrder(orderCode);
//                                dialog.dismiss();
//                            })
//                            .setNegativeButton(R.string.string_commonCancelBtn, (dialog, which) -> {
//                                dialog.dismiss();
//                                onBackPressed();
//                            })//设置对话框[否定]按钮
//                            .show();
//                } else {
//                    showDialog(getString(R.string.string_scanQRCode_errorDialogContent),
//                            R.string.string_scanQRCode_errorDialogTitleWrong);
//                }
//            } else {
//                //从主界面跳转过来
////                OrderDetailActivity_.intent(this).whichPage(OrderDetailActivity.Form_QRScanPage).orderCodeFromLastPage(orderCode).start();
//                animUtils.leftInAnimation(this);
//                onBackPressed();
//            }
//        } else {
//            showDialog(result, R.string.string_scanQRCode_errorDialogTitle);
//        }

//        if (result.contains(Value.LabelHeaderFlag) || orderCode.equals(result) || orderCode.equals("")) {
//            toConfirmOrder(result.substring(Value.LabelHeaderFlag.length()));
//        } else if (!orderCode.equals("") && !orderCode.equals(result)) {
//            showDialog("请重新扫描", R.string.string_scanQRCode_errorDialogTitleWrong);
//        } else {
//            showDialog(result, R.string.string_scanQRCode_errorDialogTitle);
//        }
    }

    /**
     * 处理扫码或粘贴的口令
     *
     * @param result
     */
    private void handleQrCode(String result, int type) {

        if (!StringUtils.isEmpty(result)) {
            try {
                String qrCode = JsonUtils.unAes(result);
                QRCodeBean bean = (QRCodeBean) JsonUtils.parseJsonString(qrCode, QRCodeBean.class);
                if (QRCodeBean.QRCodeType_TaskChang.equals(bean.getType())) {
                    TaskDetailActivity_.intent(_activity).whichPage(PageFlag.Page_ScanQrCode).taskResourceUserId(bean.getUserID()).taskId(bean.getTaskID()).start();
                    finish();
                    animUtils.leftInAnimation(_activity);
                } else {
                    handleErrAction(type);
                }
            } catch (Exception e) {
                e.printStackTrace();
                handleErrAction(type);
            }
        } else {
            handleErrAction(type);
        }
    }

    /**
     * 显示错误Toast
     *
     * @param type
     */
    private void handleErrAction(int type) {
        if (1 == type) {
            mQRCodeView.startSpot();
        }
        App.toast(1 == type ? "二维码不合法，请确认后再扫描！" : "粘贴内容不合法，请检查后再粘贴！");
    }

    /**
     * 粘贴按钮
     */
    @Click(R.id.btn_pasteQrContent)
    void onPasteQrContent() {
        ClipboardManager clipboard = (ClipboardManager) getSystemService(Context.CLIPBOARD_SERVICE);
        CharSequence charSequence = clipboard.getText();
        if (null == charSequence) {
            App.toast("您未复制任何内容，无法粘贴！");
            return;
        }
        handleQrCode(clipboard.getText().toString(), 2);
    }

//    private void showDialog(String result, int title) {
//        new AlertDialog.Builder(this)
//                .setTitle(title)//设置对话框标题
//                .setCancelable(false)
//                .setMessage(result)
//                .setPositiveButton(R.string.string_scanQRCode_errorDialogRescan, (dialog, which) -> {
//                    mQRCodeView.startSpot();
//                    dialog.dismiss();
//                })
//                .setNegativeButton(R.string.string_commonCancelBtn, (dialog, which) -> {
//                    dialog.dismiss();
//                    onBackPressed();
//                })//设置对话框[否定]按钮
//                .show();
//    }

//    /**
//     * 确认订单
//     *
//     * @param result
//     */
//    private void toConfirmOrder(String result) {
//        LocationUtil.getAndSaveLocation2SharePreference(ScanQRBarActivity.this);
//        String gps_x = SharePreferenceUtil.getLocation(ScanQRBarActivity.this).getGps_x();
//        String gps_y = SharePreferenceUtil.getLocation(ScanQRBarActivity.this).getGps_y();
//        OrderBean orderBean = new OrderBean(result, gps_x, gps_y);
//        String jsonOrderBean = JsonUtils.createJsonString(orderBean);
//        LogUtils.log("确认收货scan" + jsonOrderBean);
//
//        try {
//            String aesOrderBean = JsonUtils.aes(jsonOrderBean);
//            callNet(ScanQRBarActivity.this, InterfaceNet.Net_CompleteMission, aesOrderBean, new NetResultOperate() {
//                @Override
//                public void onSuccess(String content) {
//                    registerBordercase();
//                    App.toast("收件成功");
//                    TaskRecordListActivity_.intent(ScanQRBarActivity.this).start();
//                    animUtils.leftInAnimation(ScanQRBarActivity.this);
//                    finish();
//                }
//
//                @Override
//                public void onDataEmpty(String content) {
//
//                }
//
//                @Override
//                public void onDataEnd(String content) {
//
//                }
//            });
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }


    @Override
    public void onScanQRCodeOpenCameraError() {
        LogUtils.log("打开相机出错");
    }

//    /**
//     * 注册广播
//     */
//    private void registerBordercase() {
//        Intent intent = new Intent(Flag.BORDERCAST_CLOSE_SCAN);
//        lbm.sendBroadcast(intent);
//    }

}
